package com.autoscript.service;

import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import com.autoscript.ISystemConstant;
import com.autoscript.utils.SessionMap;
import com.dfhc.util.ConvertHelper;
import com.dfhc.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dfhc.securitydb.service.SecurityDBClientService;
import com.dfhc.util.StringHelper;
import com.autoscript.vo.UserVo;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户表服务
 * @author lsb
 * @version 1.0.0
 * @datae 2021-02-02
 */
@Service
public class UserService {
	private static Logger logger=LoggerFactory.getLogger(UserService.class);
	@Autowired
	private PublicService publicService;
	@Autowired
	private SessionMap sessionMap;
	/**
	 * 表名
	 */
	private String TABLE_NAME="AS_USER";

	/**
	 * 统计记录数
	 * @param searchMap
	 * @return
	 */
	public long count(Map<String, Object> searchMap) {
		return SecurityDBClientService.getInstance().count(getDBSesion(), TABLE_NAME, searchMap);
	}

	/**
	 *  插入
	 * @param request
	 * @throws Exception 
	 */
	public Map<String, Object> insert(HttpServletRequest request, UserVo userVo) throws Exception {
		Map<String, Object> data;
		Map<String,Object> sessionMap1 = sessionMap.get(request.getHeader(ISystemConstant.SESSION_ID));
		//校验
		if(StringHelper.isEmpty(userVo.getVerificationCode()))
			throw new Exception("手机验证码为空!");
		if(!userVo.getVerificationCode().equals(sessionMap1.get(ISystemConstant.SMS_VALIDATE_CODE)))
			throw new Exception("验证码错误!");
		else {
			logger.info("session sms verifycode:"+sessionMap1.get(ISystemConstant.SMS_VALIDATE_CODE)+",收到短信验证码:"+userVo.getVerificationCode());
			//判断验证码是否过期
			Instant sendTime = (Instant) request.getSession(false).getAttribute(ISystemConstant.SMS_VALIDATE_CODE_SEND_TIME);
			Instant now = Instant.now();
			String strEffectiveTime = publicService.getParameterValue(ISystemConstant.CODE_TYPE_SMS, ISystemConstant.CODE_DATA_SMS_EFFECTIVE_TIME);
			int effectiveTime= ConvertHelper.toInt(strEffectiveTime);
			logger.info("sendTime:"+sendTime.toString()+",strEffectiveTime:"+strEffectiveTime);
			if(Duration.between(sendTime,now).getSeconds()>effectiveTime*60)
				throw new Exception("验证码已过期!");
		}
		if(StringHelper.isEmpty(userVo.getUserName()))
			throw new Exception("用户名为空");
		//检查用户名是否存在
		Map<String,Object> checkMap = new HashMap<String,Object>();
		checkMap.put("USER_NAME",userVo.getUserName());
		if(this.count(checkMap)==1)
			throw new Exception("用户名已经被注册!");
		if(StringHelper.isEmpty(userVo.getPassword()))
			throw new Exception("密码为空");
		if(StringHelper.isEmpty(userVo.getCellPhoneNumber()))
			throw new Exception("电话号码为空");
		//检查手机号是否存在
	    checkMap.clear();
	    checkMap.put("CELL_PHONE_NUMBER",userVo.getCellPhoneNumber());
		if(this.count(checkMap)==1)
			throw new Exception("手机号已经被注册!");
		if(StringHelper.isEmpty(userVo.getEmail()))
			throw new Exception("邮箱为空");
		//检查邮箱是否存在
		checkMap.clear();
		checkMap.put("EMAIL",userVo.getEmail());
		if(this.count(checkMap)==1)
			throw new Exception("邮箱已经被注册!");
		data = new HashMap<String,Object>();
		//获取序列id
		if(StringHelper.isEmpty(userVo.getId())){
			data.put("ID",publicService.getIds(TABLE_NAME, 1)[0]);
		}
		if(!StringHelper.isEmpty(userVo.getId())){
			data.put("ID",userVo.getId());
		}
		if(!StringHelper.isEmpty(userVo.getUserName())){
			data.put("USER_NAME",userVo.getUserName());
		}
		if(!StringHelper.isEmpty(userVo.getPassword())){
			data.put("PASSWORD",userVo.getPassword());
		}
		if(!StringHelper.isEmpty(userVo.getCellPhoneNumber())){
			data.put("CELL_PHONE_NUMBER",userVo.getCellPhoneNumber());
		}
		if(!StringHelper.isEmpty(userVo.getEmail())){
			data.put("EMAIL",userVo.getEmail());
		}

		data.put("CREATE_DATE", DateUtil.getNowDate("yyyy-MM-dd HH:mm:ss"));


		data.put("IS_ENABLE", ISystemConstant.DICTIONARY_RM_YES_NOT_1);
		//默认为非管理员
		data.put("IS_ADMIN",ISystemConstant.DICTIONARY_RM_YES_NOT_0);

		int rowNum = SecurityDBClientService.getInstance().insert(getDBSesion(), TABLE_NAME, data);
		if(rowNum!=1) {
			logger.error("插入用户表失败！数据为:"+data+",rowNum:"+rowNum);
			throw new Exception("插入用户表失败！");
		}
		return data;
	}
	
	/**
	 * 获取db会话
	 * @return
	 */
	private String getDBSesion() {
		return DBSessionService.getSingleInstance().getSession();
	}
	/**
	 * 更新用户表
	 * @param userVo
	 * @return
	 * @throws Exception
	 */
	public int update(UserVo userVo) throws Exception{
		Map<String, Object> searchMap;
		Map<String, Object> data;

		if(StringHelper.isEmpty(userVo.getId()))
			throw new Exception("用户表id为空!");
		searchMap = new HashMap<String,Object>();
		
		searchMap.put("ID",userVo.getId());
		data = new HashMap<String,Object>();
		if(!StringHelper.isEmpty(userVo.getId())){
			data.put("ID",userVo.getId());
		}
		if(!StringHelper.isEmpty(userVo.getUserName())){
			data.put("USER_NAME",userVo.getUserName());
		}
		if(!StringHelper.isEmpty(userVo.getPassword())){
			data.put("PASSWORD",userVo.getPassword());
		}
		if(!StringHelper.isEmpty(userVo.getCellPhoneNumber())){
			data.put("CELL_PHONE_NUMBER",userVo.getCellPhoneNumber());
		}
		if(!StringHelper.isEmpty(userVo.getEmail())){
			data.put("EMAIL",userVo.getEmail());
		}
		if(!StringHelper.isEmpty(userVo.getCreateDate())){
			data.put("CREATE_DATE",userVo.getCreateDate());
		}
		if(!StringHelper.isEmpty(userVo.getIsEnable())){
			data.put("IS_ENABLE",userVo.getIsEnable());
		}
		int rowNum = SecurityDBClientService.getInstance().update(getDBSesion(), TABLE_NAME, searchMap, data);
		if(rowNum<1) {
			logger.error("更新用户表失败!数据为:searchMap:"+searchMap+",data:"+data+",rowNum:"+rowNum);
			throw new Exception("更新用户表失败!");
		}
		return rowNum;
	}
	/**
	 * 删除用户表
	 * @param userVo
	 * @return
	 * @throws Exception
	 */
	public int delete(UserVo userVo) throws Exception{
		Map<String,Object> searchMap = new HashMap<String,Object>();
		if(!StringHelper.isEmpty(userVo.getId())){
			searchMap.put("ID",userVo.getId());
		}
		if(!StringHelper.isEmpty(userVo.getUserName())){
			searchMap.put("USER_NAME",userVo.getUserName());
		}
		if(!StringHelper.isEmpty(userVo.getPassword())){
			searchMap.put("PASSWORD",userVo.getPassword());
		}
		if(!StringHelper.isEmpty(userVo.getCellPhoneNumber())){
			searchMap.put("CELL_PHONE_NUMBER",userVo.getCellPhoneNumber());
		}
		if(!StringHelper.isEmpty(userVo.getEmail())){
			searchMap.put("EMAIL",userVo.getEmail());
		}
		if(!StringHelper.isEmpty(userVo.getCreateDate())){
			searchMap.put("CREATE_DATE",userVo.getCreateDate());
		}
		if(!StringHelper.isEmpty(userVo.getIsEnable())){
			searchMap.put("IS_ENABLE",userVo.getIsEnable());
		}
		int rowNum = SecurityDBClientService.getInstance().delete(getDBSesion(), TABLE_NAME, searchMap);
		if(rowNum<1) {
			logger.error("删除用户表失败,参数为:"+searchMap+",rowNum:"+rowNum);
			throw new Exception("删除用户表失败!");
		}
		return rowNum;		
	}

	/**
	 * 查询用户表
	 * @param searchMap 查询条件
	 * @param pageNo 页号
	 * @param pageSize 页大小
	 * @return
	 */
	public List<Map> listPage(Map<String, Object> searchMap, int pageNo, int pageSize) {
		return SecurityDBClientService.getInstance().search(getDBSesion(), 
				TABLE_NAME, searchMap, pageNo, pageSize);
	}
	/**
	 * 查询用户表
	 * @param searchMap 查询条件
	 * @return
	 */
	public List<Map> search(Map<String, Object> searchMap) {
		return SecurityDBClientService.getInstance().search(getDBSesion(), 
				TABLE_NAME, searchMap);
	}
	/**
	 * 根据id查询用户表
	 * @param id id标识
	 * @return
	 */
	public Map getById(String id) throws Exception {
		if(StringHelper.isEmpty(id))
			throw new Exception("用户表id为空!");
		Map<String,Object> searchMap = new HashMap<String,Object>();
		
		searchMap.put("ID",id);
		List<Map> resultList =  SecurityDBClientService.getInstance().search(getDBSesion(), 
				TABLE_NAME, searchMap);
 		if(resultList==null||resultList.size()==0){
 		  return null;
 		}else{
 		  return resultList.get(0);
 		}
	}
	/**
	 *  重设用户密码
	 * @param request
	 * @param userVo
	 * @throws Exception
	 */
	public Map<String, Object> resetPassword(HttpServletRequest request, UserVo userVo) throws Exception {
		Map<String, Object> data;
		Map<String,Object> sessionMap1 = sessionMap.get(request.getHeader(ISystemConstant.SESSION_ID));
		//校验
		if(StringHelper.isEmpty(userVo.getVerificationCode()))
			throw new Exception("手机验证码为空!");
		if(!userVo.getVerificationCode().equals(sessionMap1.get(ISystemConstant.SMS_VALIDATE_CODE)))
			throw new Exception("验证码错误!");
		else {
			logger.info("session sms verifycode:"+sessionMap1.get(ISystemConstant.SMS_VALIDATE_CODE)+",收到短信验证码:"+userVo.getVerificationCode());
			//判断验证码是否过期
			Instant sendTime = (Instant) request.getSession(false).getAttribute(ISystemConstant.SMS_VALIDATE_CODE_SEND_TIME);
			Instant now = Instant.now();
			String strEffectiveTime = publicService.getParameterValue(ISystemConstant.CODE_TYPE_SMS, ISystemConstant.CODE_DATA_SMS_EFFECTIVE_TIME);
			int effectiveTime= ConvertHelper.toInt(strEffectiveTime);
			logger.info("sendTime:"+sendTime.toString()+",strEffectiveTime:"+strEffectiveTime);
			if(Duration.between(sendTime,now).getSeconds()>effectiveTime*60)
				throw new Exception("验证码已过期!");
		}
		if(StringHelper.isEmpty(userVo.getUserName()))
			throw new Exception("用户名为空");
		//检查用户名是否存在
		Map<String,Object> checkMap = new HashMap<String,Object>();
		checkMap.put("USER_NAME",userVo.getUserName());
		if(this.count(checkMap)==0)
			throw new Exception("用户名不存在!");
		if(StringHelper.isEmpty(userVo.getPassword()))
			throw new Exception("密码为空");
		if(StringHelper.isEmpty(userVo.getCellPhoneNumber()))
			throw new Exception("电话号码为空");
		//检查手机号和用户对于的手机号是否匹配
		Map<String,Object> searchMap = new HashMap<String,Object>();
		searchMap.put("CELL_PHONE_NUMBER",userVo.getCellPhoneNumber());
		searchMap.put("USER_NAME",userVo.getUserName());
		if(this.count(searchMap)==0)
			throw new Exception("手机号和用户名不匹配!");

		data = new HashMap<String,Object>();
		data.put("PASSWORD",userVo.getPassword());

		int rowNum = SecurityDBClientService.getInstance().update(getDBSesion(), TABLE_NAME,searchMap,data);
		if(rowNum!=1) {
			logger.error("重设用户表密码失败！数据为:"+data+",rowNum:"+rowNum);
			throw new Exception("重设用户表密码失败！");
		}
		return data;
	}
}
